package week07.necessary.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import week07.necessary.enums.DatasourceEnums;

@Slf4j
@Component
public class DatasourceContextHolder {
    private final ThreadLocal<DatasourceEnums> threadLocal = new ThreadLocal<>();

    public void setContext(DatasourceEnums datasourceEnums) {
        threadLocal.set(datasourceEnums);
    }

    public DatasourceEnums getContext() {
        DatasourceEnums datasourceEnums = threadLocal.get();
        if (datasourceEnums == null) {
            log.info("[动态数据源-未指定数据源枚举]使用默认数据源");
            datasourceEnums = DatasourceEnums.WRITE;
        }

        log.info("[动态数据源-本次使用]{} 数据源", datasourceEnums);
        return datasourceEnums;
    }

    public void clearContext() {
        threadLocal.remove();
    }
}
